package net.luohuasheng.bee.proxy.core.utils;

import net.luohuasheng.bee.proxy.core.exception.ConventException;
import net.luohuasheng.bee.proxy.core.utils.convert.ValueConvertUtils;

import java.util.*;

public class PropertiesUtils {

    public static <V> V getProperty(Properties properties, String key, V defaultValue) {
        Object value = properties.get(key);
        if (value == null) {
            return defaultValue;
        } else {
            try {
                return CastUtils.cast(ValueConvertUtils.convert(value, defaultValue.getClass()));
            } catch (ConventException e) {
                return defaultValue;
            }
        }
    }

    public static <V> V getProperty(Properties properties, String key, Class<V> type) {
        Object value = properties.get(key);
        if (value == null) {
            return null;
        } else {
            try {
                return CastUtils.cast(ValueConvertUtils.convert(value, type));
            } catch (ConventException e) {
                return null;
            }
        }
    }

    public static <V> Map<String, V> getPropertyMap(Properties properties, Class<V> type) {
        Map<String, V> map = new HashMap<>(0);
        for (Object key : properties.keySet()) {
            Object value = properties.get(key);
            if (type.isAssignableFrom(value.getClass())) {
                map.put(key.toString(), CastUtils.cast(value));
            }
        }
        return map;
    }

    public static <V> V getProperty(Properties properties, Class<V> type) {
        for (Object value : properties.values()) {
            if (type.isAssignableFrom(value.getClass())) {
                return CastUtils.cast(value);
            }
        }
        return null;
    }

    public static <V> List<V> getPropertys(Properties properties, Class<V> type) {
        List<V> list = new ArrayList<>(0);
        for (Object value : properties.values()) {
            if (type.isAssignableFrom(value.getClass())) {
                list.add(CastUtils.cast(value));
            }
        }
        return list;
    }
}
